#include "ComponentTemplate.h"
#include "ECS.h"

#include <TinyXML/tinyxml.h>
#include <map>
#include "MetaTable.h"
#include "TextUtils.h"
#include "StringHash.h"

namespace ECS
{
	void ComponentTemplate::initComponent(Component* component)
	{
		// init public members
		for (auto it = values.begin(); it != values.end(); ++it)
		{
			MemberValue* v = *it;
			v->setValue(component);
		}

		// connect slots
	}

	Component* ComponentTemplate::create()
	{
		Component* component = (Component*)classTable->construct();
		initComponent(component);

		return component;
	}

	void ComponentTemplate::afterInit( Component* component )
	{
		Assembly* assembly = component->getAssembly();
		for (auto it = connections.begin(); it != connections.end(); ++it)
		{
			const ComponentConnection& connection = *it;
			MetaClass* sourceTable = nullptr;
			void* source = nullptr;

			if (assembly->getMetaTable()->isSubclass(connection.component))
			{
				sourceTable = assembly->getMetaTable();
				source = assembly;
			}
			else
			{
				Component* componentSource = assembly->getComponent(connection.component);
				if (!componentSource)
					continue;

				source = componentSource;
				sourceTable = componentSource->getMetaTable();
			}

			MetaSignal* signal = sourceTable->getSignal(connection.signal);
			if (!signal)
				continue;

			MetaFunction* slot = component->getMetaTable()->getMethod(connection.slot, signal->signature, true);
			if (!slot)
				continue;

			signal->connect(source, component, slot);
		}
	}

}